<?php
//解析session_set_save_handler session 序列号
function sess_un($data_value) {
	 $vars = preg_split(
		 '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',
		 $data_value, -1, PREG_SPLIT_NO_EMPTY |
		 PREG_SPLIT_DELIM_CAPTURE
	 );
	 for ($i = 0; isset($vars[$i]); $i++) {
		 $result[$vars[$i++]] = unserialize($vars[$i]);
	 }
	 return $result;
}
//ajax JSON.stringify(data); 返回处理
function form_ajaxs($arguments){
		$data=array();
		$data_arr = json_decode(cypto_d($arguments),true);
		if(!isset($data_arr)){
				ajax_return(0,'不能有&等特殊字符');
		}
		foreach($data_arr as $key=>$val){
			$k=$val['name'];
			$v=$val['value'];
			if(isset($data[$k])){
				$data[$k].="_".$v;
			}else{
				$data[$k]=$v;
			}
		}
		return $data;
}
function msg_error($str){
    echo '<meta charset="utf-8">';
    trigger_error($str, E_USER_ERROR);exit;
}
/**
* 内部码：及代表含义
* @param undefined $code
*
* @return
*/
function ajax_return($status,$msg,$data=false){
	$ajax_return['msg']=$msg;
	$ajax_return['status']=$status;
	$ajax_return['data']=$data;
	echo json_encode($ajax_return);exit;
}
/**
* 正则验证
* @return
*/
function check_regex($value,$rule) {
    $validate = array(
    		'istell'    =>  '/^([0-9]{3,4}-)?[0-9]{7,8}$/',//tell 验证
    		'ismobile'  =>  '/^1[3|4|5|7|8][0-9]\d{8}$/',//手机
            'email'     =>  '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',//邮箱
            'url'       =>  '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(:\d+)?(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
            'number'    =>  '/^\d+$/',
            'integer'   =>  '/^[-\+]?\d+$/',
            'double'    =>  '/^[-\+]?\d+(\.\d+)?$/',
            'english'   =>  '/^[A-Za-z]+$/',
            'englishh'   =>  '/^[A-Za-z|]+$/',//只能是字母和|
            'englishx'  =>  '/^[A-Za-z_]+$/',//字母加下划线
            'isnozh'    =>	'/^[a-zA-Z0-9]+$/',
            'dir'      	=>	'/^[a-zA-Z0-9_\/]+$/',//目录结果
            'card'		=>  '/^(\d{18,18}|\d{15,15}|\d{17,17}x)$/',
            'price'     =>  "/^\d+\.?\d{0,2}$/",
            'iszhen'    =>  '/[\x7f-\xff]/',//存在中文 no 不存在中文
            'iszhen2'   =>  '/^[\x{4e00}-\x{9fa5}]+$/u',//全是中文  no 不全是中文
            'comstrunderline'    =>  '/^[0-9a-zA-Z_\x{4e00}-\x{9fa5}]+$/iu',//中文 英文 数字 下划线
			'title'    =>  '/^[0-9a-zA-Z\?\。\x{4e00}-\x{9fa5}]+$/iu',//中文 英文 数字 下划线 ? .
            'comstr'    =>  '/^[0-9a-zA-Z\x{4e00}-\x{9fa5}]+$/iu',//中文 英文 数字
            'filename'	=> 	'/^[A-Za-z0-9_.]+$/',//文件名验证
			'width'	=>'/^(\d+)|(\d+%)$/',//宽带+百分比
        );
        // 检查是否有内置的正则表达式
        if(isset($validate[strtolower($rule)]))
            $rule = $validate[strtolower($rule)];
        return preg_match($rule,$value)===1;
}
//str_safe safe 处理
function str_safe($str,$rule='escape'){
	if($rule=='escape'){//转义
    	return addslashes($str);
	}elseif($rule=='noescape'){//反转
		//if (get_magic_quotes_gpc()) {
    		return stripslashes($str);
		//}else{
	    //	return $str;
		//}
	}elseif($rule=='entity'){//html 添加实体
		return htmlspecialchars($str);
	}elseif($rule=='noentity'){//解封html 实体
		return htmlspecialchars_decode($str);
	}elseif($rule=='delhtmllable'){//去掉字符串中的html 实体
		return strip_tags($str);
	}elseif($rule=='enter_br'){//将字符中的回车替换成<br>;
		return nl2br($str);
	}
}
//截取字符串长度
function cms_msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
        if(function_exists("mb_substr"))
            $slice = mb_substr($str, $start, $length, $charset);
        elseif(function_exists('iconv_substr')) {
            $slice = iconv_substr($str,$start,$length,$charset);
        }else{
            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        return $suffix ? $slice.'...' : $slice;
    }
/**
* 验证长度
* 在$start 和 $end 之间 return true; 反之return false;
* @如果只有$start 小于$satrt return true;反之return false;
*/
function cms_length($str,$start='',$end=''){
	$length=strlen($str);
	if($start && $end){
		if($length<$start || $length>$end){
			return false;
		}else{
			return true;
		}
	}elseif($start && $end==''){
		if($length<$start){
			return false;
		}else{
			return true;
		}
	}
}
/**
 * UTF-8编码 GBK编码相互转换/（支持数组）
 *
 * @param array $str   字符串，支持数组传递
 * @param string $in_charset 原字符串编码
 * @param string $out_charset 输出的字符串编码
 * @return array
 */
function cms_iconv($str,$in_charset='gbk',$out_charset='utf-8'){
	if(is_array($str)){
		foreach($str as $k=>$v){
			$str[$k]=cms_iconv($v);
		}
		return $str;
	}elseif(is_string($str)){
		return mb_convert_encoding($str, $out_charset, $in_charset);
	}else{
		return $str;
	}
}
//自动获取字符串编码函数
function icon_encoding($str){
	return mb_detect_encoding($str,mb_detect_order(),false);
}

function encrypt($string,$operation,$key=''){
    $key=md5($key);
    $key_length=strlen($key);
    $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
    $string_length=strlen($string);
    $rndkey=$box=array();
    $result='';
    for($i=0;$i<=255;$i++){
           $rndkey[$i]=ord($key[$i%$key_length]);
        $box[$i]=$i;
    }
    for($j=$i=0;$i<256;$i++){
        $j=($j+$box[$i]+$rndkey[$i])%256;
        $tmp=$box[$i];
        $box[$i]=$box[$j];
        $box[$j]=$tmp;
    }
    for($a=$j=$i=0;$i<$string_length;$i++){
        $a=($a+1)%256;
        $j=($j+$box[$a])%256;
        $tmp=$box[$a];
        $box[$a]=$box[$j];
        $box[$j]=$tmp;
        $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
    }
    if($operation=='D'){
        if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
            return substr($result,8);
        }else{
            return'';
        }
    }else{
        return str_replace('=','',base64_encode($result));
    }
}
//函数encrypt($string,$operation,$key)中$string：需要加密解密的字符串；$operation：判断是加密还是解密，E表示加密，D表示解密；$key：密匙。

function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if(isset($_SERVER['HTTP_X_REAL_IP'])){//nginx 代理模式下，获取客户端真实IP
        $ip=$_SERVER['HTTP_X_REAL_IP'];
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
    }else{
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
* 返回访问设备
*
* @return
*/
function cms_agent(){
	$agent=strtolower($_SERVER['HTTP_USER_AGENT']);
	if(strpos($agent,'windows nt')){
		$platform = 'windows';
	}elseif(strpos($agent,'macintosh')){
		$platform="mac";
	}elseif(strpos($agent,'ipod')){
		$platform="ipod";
	}elseif(strpos($agent,'ipad')){
		$platform="ipad";
	}elseif(strpos($agent,'iphone')){
		$platform="iphone";
	}elseif(strpos($agent,'android')){
		$platform="android";
	}elseif(strpos($agent,'linux')){
		$platform="linux";
	}elseif(strpos($agent, 'unix')){
		$platform="unix";
	}else{
		$platform="other";
	}
	return $platform;
}
function cms_is_mobile(){
	$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
	$mobile_browser = '0';
	if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
		$mobile_browser++;
	if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
		$mobile_browser++;
	if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
	 	$mobile_browser++;
	if(isset($_SERVER['HTTP_PROFILE']))
	 	$mobile_browser++;
	 $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
	 $mobile_agents = array(
			'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
			'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
			'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
			'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
			'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
			'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
			'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
			'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
			'wapr','webc','winw','winw','xda','xda-'
	 );
	if(in_array($mobile_ua, $mobile_agents))
		 $mobile_browser++;
	if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
		 $mobile_browser++;
	 // Pre-final check to reset everything if the user is on Windows
	if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
		 $mobile_browser=0;
		 // But WP7 is also Windows, with a slightly different characteristic
	if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
		$mobile_browser++;
	if($mobile_browser>0)
		return true;
 	else
		return false;
}
//更改配置文件信息 php数组$data 写入文件的数组
function setFileConfig($name,$data=array(),$ext='php',$dir=''){
	if(empty($data)){
		return false;
	}
	if($dir==''){
		$dir=_CONFIG;
	}
	//写入配置文件数组
	$file=$dir.$name.".".$ext;
	if(!is_file($file)){
		msg_error($file.'文件不存在');
	}
	if(file_upext($file,$ext,$data)){
		return true;
	}else{
		return false;
	}
}
//获取文件信息
function getFileConfig($name,$dir='',$exts='php'){
	static $cmsconfig=array();
	if($dir==''){$dir=_CONFIG;}
	$file=$dir.$name.'.'.$exts;
	if(!is_file($file)){
		msg_error($file.'文件不存在');
	}
   	$cmsconfig[$name]=file_ext($file);
    return $cmsconfig[$name];
}
//加载目录下的配置 文件
function load_confog($dir){
	if(is_dir($dir)){
		$handler = opendir($dir);
		while (($filename = readdir($handler)) !== false){
		//务必使用!==，防止目录下出现类似文件名“0”等情况
	        if ($filename != "." && $filename != ".."){
	        	$file=$dir.'/'.$filename;
	        	$ext  = pathinfo($file,PATHINFO_EXTENSION);
                if(is_file($file)){
                    $_config=file_ext($file);
                    if(!empty($_config)){
						getConfig($_config);
					}
                }
	        }
    	}
   	 	closedir($handler);
	}
	return true;
}
//获取配置value
function getConfig($name=null, $value=null,$default=null) {
    static $_config = array();
    // 无参数时获取所有
    if (empty($name)) {
        return $_config;
    }
    // 优先执行设置获取或赋值
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtolower($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : $default;
            $_config[$name] = $value;
            return null;
        }
        // 二维数组设置和获取支持
        $name = explode('.', $name);
        $name[0]   =  strtolower($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
        $_config[$name[0]][$name[1]] = $value;
        return null;
    }
    // 批量设置
    if (is_array($name)){
        $_config = array_merge($_config, array_change_key_case($name,CASE_LOWER));
        return null;
    }
    return null; // 避免非法参数
}


//文件类型管理
function file_ext($file){
	//获取扩展名
	$arr=explode('.', $file);
	$exts= end($arr);
	switch($exts){
        case 'php':
            return require($file);
        case 'ini':
            return parse_ini_file($file);
        case 'yaml':null;
          	return yaml_parse_file($file);
        case 'xml':
            return (array)simplexml_load_file($file);
        case 'json':
           	return json_decode(file_get_contents($file), true);
        default:
        	return null;
    }
}
function file_upext($file,$ext='php',$data=array()){
	switch($ext){
        case 'php':
            $return='<?php return '.var_export($data,true)." ?>";
            break;
        case 'ini':
            $return='待完善';break;
        case 'yaml':
            $return='待完善';break;
        case 'xml':
            $return='待完善';break;
        case 'json':
            $return='待完善';break;
        default:$return=null;break;
    }
	return file_put_contents($file,$return);
}
//数组排序.//排序比较时 要用数字；
function array_sort($array=array(),$keys,$type='asc'){
   $keysvalue = $new_array = array();
   //提取排序的列
   foreach ($array as $k=>$v){
       $keysvalue[$k] = $v[$keys];
   }
   if($type == 'asc'){
       asort($keysvalue);//升序排列
   }else{
       arsort($keysvalue);//降序排列
   }
   //reset($keysvalue);
   foreach ($keysvalue as $k=>$v){
       $new_array[$k] = $array[$k];
   }
   return $new_array;
}
//获取某一时间的开始时间和结束时间 $t=time();
function start_end_time($t=null){
	if($t===null){
		$t=time();
	}
	$data=array();
	$data['start_time'] = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));  //当天开始时间
	$data['end_time'] = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t)); //当天结束时间
	return $data;
}
//删除字符串中 字符bom
function bom_delete($contents){
	$BOM = chr(239).chr(187).chr(191);
	$contents=str_replace($BOM,'',$contents);
	return $contents;
}
//文件权限r=4 w=2 x=1  返回当前权限值 
function file_auth($file){
	$value=0;
	if(is_readable($file)){//读
		$value+=4;
	}
	if(is_writable($file)){//写
		$value+=2;
	}
	if(is_executable($file)){//执行
		$value+=1;
	}
	return $value;
}
//错误关闭与开启
function is_site_error($type=false){
	if($type==false){
		ini_set("display_errors", "Off");
		error_reporting(0);
	}else{
		ini_set("display_errors", "On");
		error_reporting(E_ALL);
	}
}
//结合js 进行加密
function cypto_e($str){
    return base64_encode(urlencode($str));
}
//结合js 进行解密
function cypto_d($str){
    return urldecode(base64_decode($str));
}
//字符串中的常量处理
function define_constant($str){
	return constant($str);
}
//唯一标识
function guidstr($str=false) {
	     $charid = strtoupper(md5(uniqid(mt_rand(), true)));
	    $uuid =substr($charid, 0, 8)
	    .substr($charid, 8, 4)
	    .substr($charid,12, 4)
	    .substr($charid,16, 4)
	    .substr($charid,20,12);
	    if($str!==false){
	    	 return md5($uuid.$str);
	    }
	    return md5($uuid);
}
/**
* 产生随机字符串
* 数字及字母
* @param    int        $length  输出长度
* @param    string     $chars   可选的 ，默认为 0123456789
* @return   string     字符串
*/
function getstr($length){
	$hash = '';
	//第一位不能为0；
	$charsone="123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
	$maxone = strlen($charsone) - 1;
	$hash.= $charsone[mt_rand(0, $maxone)];

	$chars = '0123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
	$max = strlen($chars) - 1;
	for($i = 0; $i < $length-1; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}
//登陆密码加密
function passcreate($password){
	$p1=hash("sha256",$password."eduadmin");
	return md5($p1."eduadmin");
}
function each_replace(&$array){
   $res = array();
   $key = key($array);
   if($key !== null){
       next($array); 
       $res[1] = $res['value'] = $array[$key];
       $res[0] = $res['key'] = $key;
   }else{
       $res = false;
   }
   return $res;
}
?>
